package org.libermundi.theorcs.chronicles.model.message;

import java.util.ArrayList;
import java.util.List;
import java.util.SortedSet;

import javax.persistence.Basic;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.persistence.Transient;

import org.hibernate.annotations.Fetch;
import org.hibernate.annotations.FetchMode;
import org.hibernate.annotations.Sort;
import org.hibernate.annotations.SortType;
import org.libermundi.theorcs.chronicles.ChronicleConstants;
import org.libermundi.theorcs.chronicles.model.Persona;
import org.libermundi.theorcs.core.model.base.BasicEntity;

import com.google.common.collect.ImmutableList;

@Entity(name="AddressBook")
@Table(name=ChronicleConstants.TBL_ADDRESSBOOK)
public final class AddressBook extends BasicEntity {

	private static final long serialVersionUID = 1714920993503485810L;

	public final static String PROP_NAME="name";
	
	public final static String PROP_OWNER="owner";

	private String _name="Default"; // I don't plan to use it now... Just in case we make many address books one day.
	
	private Persona _owner;
	
	private SortedSet<Persona> _contacts;
	
	@Basic
	@Column(name = AddressBook.PROP_NAME, length=50, nullable=false)
	public String getName() {
		return _name;
	}
	
	@ManyToOne(cascade = CascadeType.ALL,fetch=FetchType.LAZY)
	@JoinColumn(name="ownerId")
	public Persona getOwner(){
		return _owner;
	}
	
	@ManyToMany(fetch=FetchType.LAZY)
	@Sort(type=SortType.NATURAL)
	@JoinTable(name = ChronicleConstants.TBL_CONTACT, 
			joinColumns = { @JoinColumn(name = "addressBookId", referencedColumnName="id") }, 
			inverseJoinColumns = { 
				@JoinColumn( name="contactId", referencedColumnName="id")
			} 
	)
	@Fetch(FetchMode.SELECT)
	public SortedSet<Persona> getContacts() {
		return _contacts;
	}
	
	@Transient
	public List<Persona> getContactsAsList() {
		return (getContacts()==null) ? new ArrayList<Persona>() : ImmutableList.copyOf(getContacts());
	}
	
	public void setName(String name) {
		_name = name;
	}

	public void setOwner(Persona owner) {
		_owner = owner;
	}
	
	public void setContacts(SortedSet<Persona> contacts){
		_contacts = contacts;
	}
	
	@Override
	public String toString() {
		return "AddressBook [id=" + getId() + ", Owner=" + _owner.getName() + ", name=" + _name + ", Nbre of Contacts=" + ((getContacts()==null) ? 0: getContacts().size()) + "]";
	}	
}
